package com.example.permissionservice.service.impl;

import com.example.common.constant.RoleConstant;
import com.example.common.exception.BusinessException;
import com.example.common.exception.NotFoundException;
import com.example.permissionservice.entity.RoleEntity;
import com.example.permissionservice.entity.UserRoleEntity;
import com.example.permissionservice.repository.RoleRepository;
import com.example.permissionservice.repository.UserRoleRepository;
import com.example.permissionservice.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class PermissionServiceImpl implements PermissionService {

    private final RoleRepository roleRepository;
    private final UserRoleRepository userRoleRepository;

    @Autowired
    public PermissionServiceImpl(RoleRepository roleRepository,
                                 UserRoleRepository userRoleRepository) {
        this.roleRepository = roleRepository;
        this.userRoleRepository = userRoleRepository;
    }

    @Override
    @Transactional
    public void bindDefaultRole(Long userId) {
        // 检查是否已绑定
        if (userRoleRepository.existsByUserId(userId)) {
            return;
        }

        // 获取默认角色 (普通用户)
        RoleEntity defaultRole = roleRepository.findByRoleCode(RoleConstant.USER)
                .orElseThrow(() -> new NotFoundException("默认角色未配置"));

        UserRoleEntity userRole = new UserRoleEntity();
        userRole.setUserId(userId);
        userRole.setRoleId(defaultRole.getRoleId());
        userRoleRepository.save(userRole);
    }

    @Override
    public String getUserRoleCode(Long userId) {
        // 使用Optional处理可能为空的情况
        Optional<UserRoleEntity> userRoleOpt = userRoleRepository.findByUserId(userId);

        if (!userRoleOpt.isPresent()) {
            throw new NotFoundException("用户角色未绑定");
        }

        Integer roleId = userRoleOpt.get().getRoleId();

        // 使用Optional获取角色
        Optional<RoleEntity> roleOpt = roleRepository.findById(roleId);

        return roleOpt.map(RoleEntity::getRoleCode)
                .orElseThrow(() -> new NotFoundException("角色不存在"));
    }

    @Override
    @Transactional
    public void upgradeToAdmin(Long userId) {
        changeUserRole(userId, RoleConstant.ADMIN);
    }

    @Override
    @Transactional
    public void downgradeToUser(Long userId) {
        changeUserRole(userId, RoleConstant.USER);
    }

    private void changeUserRole(Long userId, String targetRoleCode) {
        // 获取目标角色
        RoleEntity targetRole = roleRepository.findByRoleCode(targetRoleCode)
                .orElseThrow(() -> new NotFoundException("角色不存在: " + targetRoleCode));

        // 查找现有绑定
        Optional<UserRoleEntity> userRoleOpt = userRoleRepository.findByUserId(userId);

        if (!userRoleOpt.isPresent()) {
            throw new NotFoundException("用户角色未绑定");
        }

        UserRoleEntity userRole = userRoleOpt.get();

        // 检查是否已经是目标角色
        if (userRole.getRoleId().equals(targetRole.getRoleId())) {
            return;
        }

        // 更新角色绑定
        userRole.setRoleId(targetRole.getRoleId());
        userRoleRepository.save(userRole);
    }
}